package com.wlr.study.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lerong.wang
 * @version 1.0.0
 * @description
 * @date 2025/1/8 15:17
 */
public class LeetCode216 {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(n, k, 1, 0);
        return result;
    }

    public void backtracking(int n, int k, int startIndex, int sum) {
        // 减枝
        if (sum > n) {
            return;
        }

        if (path.size() == k) {
            if (sum == n) result.add(new ArrayList<>(path));
            return;
        }

        // 减枝 9 - (k - path.size()) + 1
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            sum += i;
            backtracking(n, k, i + 1, sum);
            //回溯
            path.removeLast();
            //回溯
            sum -= i;
        }

    }

    public static void main(String[] args) {
        LeetCode216 leetCode216 = new LeetCode216();
        List<List<Integer>> lists = leetCode216.combinationSum3(3, 7);
        System.out.println(lists);
    }
}